package com.ufo.store.management.ui.activity;

import android.app.SharedElementCallback;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.Pair;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.transition.ChangeImageTransform;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.transition.TransitionManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.UrlSafeBase64;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.Isszmbalv3BranchInfo;
import com.ufo.store.management.entity.Isszmbalv3StockInfo;
import com.ufo.store.management.entity.Isszmbalv3SupcustInfo;
import com.ufo.store.management.entity.QiniuControl;
import com.ufo.store.management.entity.SerializableList;
import com.ufo.store.management.entity.SerializableMap;
import com.ufo.store.management.entity.ServiceResult;
import com.ufo.store.management.net.NetCallback;
import com.ufo.store.management.net.NetHelper;
import com.ufo.store.management.utils.Auth;
import com.ufo.store.management.utils.DialogUtil;
import com.ufo.store.management.utils.GlideUtils;
import com.ufo.store.management.utils.PhotoUtils;
import com.ufo.store.management.utils.StatusBarUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.view.FloatTextToast;
import com.ufo.store.management.widget.dialog.PickImageDialog;
import com.ufo.store.management.widget.dialog.ProtogenesisInputDialog;
import com.ufo.store.management.widget.zxing.MipcaActivityCapture;

import org.json.JSONObject;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.ufo.store.management.BarApplication.mSavePictureDirPath;

/**
 * Created by taoli on 2016/12/13 0013.
 */

public class Isszmbalv3StockEditActivity extends BaseActivity {
    public static final String VIEW_NAME_HEADER_IMAGE = "detail:header:image";
    public static final String VIEW_NAME_HEADER_TITLE = "detail:header:title";
    public static final String VIW_NAME_HEAD_TOOLBAR = "detail:header:toolbar";
    private final int ACTIVITY_RESULT_BRANDECODE = 1;
    private AppBarLayout appBarLayout;
    private Toolbar toolBar;
    private CollapsingToolbarLayout coordinatorLayout;
    private ImageView mStockIconIv = null;

    private EditText mStockIdEt = null;
    private EditText mStockNameEt = null;
    private EditText mStockSpellEt = null;
    private EditText mStockUnitEt = null;
    private EditText mStockTypeidEt = null;
    private EditText mStockPriceEt = null;
    private EditText mStockRetailPriceEt = null;
    private TextView mStockVipAccFlagTv = null;
    private EditText mStockSupcustEt = null;

    private ImageButton mStockIdIb = null;
    private ImageButton mStockSupcustdIb = null;
    private Switch mStockVipAccFlagSB = null;

    //传入参数
    private Isszmbalv3StockInfo mIsszmbalv3StockInfo = null;
    private boolean mbIsInsertData = true;

    private int mUnitType = -1;
    private SerializableMap mIsszmbalv3StockTypeMap = new SerializableMap();
    private List<Isszmbalv3SupcustInfo> mIsszmbalv3SupcustInfo = null;
    private String mIsszmbalv3MaxDispersionIndex = "";

    //图像显示保存
    private Configuration qiniuConfig;

    private PickImageDialog mPickImageDialog = null;
    private String mPicDescPath = null;
    private PhotoUtils mPhotoUtils;

    private boolean mIsReturning = false;
    /**
     * @desc
     * @author taoli
     * @time 2017/10/10 0010
     * 0:EXPANDED(展开)   1:COLLAPSED(折叠)   2:INTERNEDIATE(中间)
     */
    private int state = 0;
    private AppBarLayout.OnOffsetChangedListener onOffsetChangedListener = new AppBarLayout.OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            //i>=0  Toolbar全部显示
            if (verticalOffset == 0) {
                //修改状态标记为展开
                if (state != 0) {
                    state = 0;
                    toolBar.setNavigationIcon(R.drawable.ic_back_selector);
                    invalidateOptionsMenu();
                    StatusBarUtil.StatusBarLightMode(Isszmbalv3StockEditActivity.this, R.color.transparent, false);
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                //修改状态标记为折叠
                if (state != 1) {
                    state = 1;
                    toolBar.setNavigationIcon(R.drawable.ic_back_light_selector);
                    invalidateOptionsMenu();
                    StatusBarUtil.setStatusBarColor(Isszmbalv3StockEditActivity.this, R.color.transparent, false);
                }
            } else {
                //修改状态标记为中间
                if (state != 2) {
                    state = 2;
                }
            }
        }
    };
    private Toolbar.OnMenuItemClickListener onMenuItemClickListener = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_save:
                    submitIsszmbalv3StockEdit();
                    break;
                case R.id.action_queue:
                    pickPicDescImage();
                    break;
            }
            return true;
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (state == 0) {
            getMenuInflater().inflate(R.menu.stockedit_dark_menu, menu);
        } else if (state == 1) {
            getMenuInflater().inflate(R.menu.stockedit_light_menu, menu);
        }
        return true;
    }

    /**
     * Schedules the shared element transition to be started immediately
     * after the shared element has been measured and laid out within the
     * activity's view hierarchy. Some common places where it might make
     * sense to call this method are:
     * <p>
     * (1) Inside a Fragment's onCreateView() method (if the shared element
     * lives inside a Fragment hosted by the called Activity).
     * <p>
     * (2) Inside a Picasso Callback object (if you need to wait for Picasso to
     * asynchronously load/scale a bitmap before the transition can begin).
     * <p>
     * (3) Inside a LoaderCallback's onLoadFinished() method (if the shared
     * element depends on data queried by a Loader).
     */
    private void scheduleStartPostponedTransition(final View sharedElement) {
        sharedElement.getViewTreeObserver().addOnPreDrawListener(
                new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        sharedElement.getViewTreeObserver().removeOnPreDrawListener(this);
                        startPostponedEnterTransition();
                        return true;
                    }
                });
    }

    @Override
    public void finishAfterTransition() {
        mIsReturning = true;
        super.finishAfterTransition();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                mIsszmbalv3StockInfo = (Isszmbalv3StockInfo) bundle.getSerializable("Isszmbalv3StockInfo");
                mIsszmbalv3StockTypeMap = (SerializableMap) bundle.getSerializable("Isszmbalv3StockType");
                //SerializableList list = (SerializableList) bundle.getSerializable("Isszmbalv3SupcustInfo");
                //mIsszmbalv3SupcustInfo = list.getIsszmbalv3SupcustInfoList();
                if (mIsszmbalv3StockInfo != null)
                    mbIsInsertData = false;
                else {
                    mIsszmbalv3StockInfo = new Isszmbalv3StockInfo();
                }
            }
        }

        qiniuConfig = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        mPhotoUtils = new PhotoUtils(new PhotoUtils.OnPhotoResultListener() {
            @Override
            public void onPhotoResult(Uri uri) {
                if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
                    mPicDescPath = Utils.getPath(Isszmbalv3StockEditActivity.this, uri);
                    if (!TextUtils.isEmpty(mPicDescPath)) {
                        GlideUtils.LoadImageWithLocation(getActivity(), mPicDescPath, mStockIconIv);
                    }
                }
            }

            @Override
            public void onPhotoCancel() {
            }
        });
    }

    private void initView() {
        setContentView(R.layout.activity_isszmbalv3_stock_edit);
        postponeEnterTransition();
        StatusBarUtil.StatusBarLightMode(Isszmbalv3StockEditActivity.this, R.color.transparent, false);
        toolBar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolBar);
        toolBar.setNavigationIcon(R.drawable.ic_back_selector);
        toolBar.setOnMenuItemClickListener(onMenuItemClickListener);
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAfterTransition();
            }
        });
        this.setEnterSharedElementCallback(new SharedElementCallback() {
            @Override
            public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
                if (mIsReturning) {
                    //折叠状态清楚共享动画
                    if (state == 1) {
                        // If shared element is null, then it has been scrolled off screen and
                        // no longer visible. In this case we cancel the shared element transition by
                        // removing the shared element from the shared elements map.
                        names.clear();
                        sharedElements.clear();
                    }
                }
                super.onMapSharedElements(names, sharedElements);
            }

            @Override
            public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots) {
                super.onSharedElementEnd(sharedElementNames, sharedElements, sharedElementSnapshots);
                if (mIsReturning) {
                   // toolBar.setVisibility(View.INVISIBLE);
                } else {
                   // toolBar.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots) {
                super.onSharedElementStart(sharedElementNames, sharedElements, sharedElementSnapshots);
            }

            @Override
            public void onSharedElementsArrived(List<String> sharedElementNames, List<View> sharedElements, SharedElementCallback.OnSharedElementsReadyListener listener) {
                super.onSharedElementsArrived(sharedElementNames, sharedElements, listener);
            }
        });
        coordinatorLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
        appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);

        mStockIconIv = (ImageView) findViewById(R.id.stock_icon_iv);
        mStockIconIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                ArrayList list = new ArrayList();
                ArrayList<String> imgUrlList = new ArrayList<>();
                ArrayList<String> imgDescriptionList = new ArrayList<>();
                if (mIsszmbalv3StockInfo != null && !TextUtils.isEmpty(mIsszmbalv3StockInfo.item_name)) {
                    //imgUrlList.add(BarApplication.Qiniu_BaseDownloadHost + BarApplication.mStoreName + "_" + "stockNo_" + mIsszmbalv3StockInfo.item_no.trim() + ".jpg");
                    imgUrlList.add("file://" + mSavePictureDirPath + BarApplication.mStoreName + "_" + "stockNo_" + mIsszmbalv3StockInfo.item_no.trim() + ".jpg");
                    imgDescriptionList.add(mIsszmbalv3StockInfo.item_name);
                }
                list.add(imgUrlList);
                list.add(imgDescriptionList);
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("list", list);
                bundle.putInt("pos", 0);
                intent.setClass(Isszmbalv3StockEditActivity.this, PictureViewActivity.class);
                intent.putExtras(bundle);

                Pair<View, String> pImage = Pair.create(v, Isszmbalv3StockEditActivity.VIEW_NAME_HEADER_IMAGE);
                ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
                getActivity(), pImage);
                startActivity(intent, activityOptions.toBundle());
            }
        });
        scheduleStartPostponedTransition(mStockIconIv);

        mStockIdEt = (EditText) findViewById(R.id.stock_id_et);
        mStockNameEt = (EditText) findViewById(R.id.stock_name_et);
        mStockSpellEt = (EditText) findViewById(R.id.stock_spell_et);
        mStockUnitEt = (EditText) findViewById(R.id.stock_unit_et);
        mStockTypeidEt = (EditText) findViewById(R.id.stock_typeid_et);
        mStockPriceEt = (EditText) findViewById(R.id.stock_price_et);
        mStockRetailPriceEt = (EditText) findViewById(R.id.stock_retail_price_et);
        mStockVipAccFlagTv = (TextView) findViewById(R.id.stock_vip_acc_flag_tv);
        mStockIdIb = (ImageButton) findViewById(R.id.stock_id_bt);
        mStockSupcustEt = (EditText) findViewById(R.id.stock_supcustd_et);
        mStockSupcustdIb = (ImageButton) findViewById(R.id.stock_supcustd_bt);

        mStockVipAccFlagSB = (Switch) findViewById(R.id.stock_vip_acc_flag_sb);
        mStockVipAccFlagSB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mStockVipAccFlagTv.setText("积分");
                    mIsszmbalv3StockInfo.vip_acc_flag = "1";
                } else {
                    mStockVipAccFlagTv.setText("不积分");
                    mIsszmbalv3StockInfo.vip_acc_flag = "0";
                }
            }
        });

        mStockNameEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String chineseSpell = Utils.cn2FirstSpell(s.toString());
                mStockSpellEt.setText(chineseSpell);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        if (mIsszmbalv3StockInfo != null) {
            if (!TextUtils.isEmpty(mIsszmbalv3StockInfo.item_no)) {
                getPicDesc(mIsszmbalv3StockInfo.item_no.trim(), mStockIconIv);
                TextView titleTv = new TextView(this);
                titleTv.setTextColor(ContextCompat.getColor(this, R.color.black));
                titleTv.setTextSize(20);
                titleTv.setGravity(Gravity.CENTER);
                titleTv.setTransitionName(VIW_NAME_HEAD_TOOLBAR);
                titleTv.getPaint().setFakeBoldText(true);
                Toolbar.LayoutParams layoutParams = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT;
                titleTv.setLayoutParams(layoutParams);
                try {
                    String path = mSavePictureDirPath + BarApplication.mStoreName + "_" + "stockNo_" + mIsszmbalv3StockInfo.item_no.trim() + ".jpg";
                    File f = new File(path);
                    if (!f.exists()) {
                        if (!TextUtils.isEmpty(mIsszmbalv3StockInfo.item_name.trim())) {
                            titleTv.setText(mIsszmbalv3StockInfo.item_name.trim());
                        } else {
                            titleTv.setText("商品详情");
                        }
                        toolBar.addView(titleTv);
                        coordinatorLayout.setCollapsedTitleTextColor(Color.parseColor("#ff000000"));
                        coordinatorLayout.setExpandedTitleColor(Color.parseColor("#00000000"));
                    } else {
                        coordinatorLayout.setCollapsedTitleTextColor(Color.parseColor("#ffffffff"));
                        coordinatorLayout.setExpandedTitleColor(Color.parseColor("#00ffffff"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mStockIdEt.setText(mIsszmbalv3StockInfo.item_no.trim());
            mStockNameEt.setText(mIsszmbalv3StockInfo.item_name);
            mStockSpellEt.setText(mIsszmbalv3StockInfo.item_rem);
            mStockPriceEt.setText(String.valueOf(mIsszmbalv3StockInfo.price));
            mStockRetailPriceEt.setText(String.valueOf(mIsszmbalv3StockInfo.sale_price));
            if (mIsszmbalv3StockInfo.measure_flag.contains("0")) {
                mUnitType = 0;
                mStockUnitEt.setText("普通（袋装扫码）");
            } else if (mIsszmbalv3StockInfo.measure_flag.contains("1")) {
                mUnitType = 1;
                mStockUnitEt.setText("计重（按公斤）");
            }
            if (mIsszmbalv3StockInfo.vip_acc_flag.contains("1")) {
                mStockVipAccFlagTv.setText("积分");
                mStockVipAccFlagSB.setChecked(true);
            } else {
                mStockVipAccFlagTv.setText("不积分");
                mStockVipAccFlagSB.setChecked(false);
            }

            String typename = mIsszmbalv3StockTypeMap.getMap().get(mIsszmbalv3StockInfo.item_clsno);
            if (!TextUtils.isEmpty(typename))
                mStockTypeidEt.setText(typename);

            if (!TextUtils.isEmpty(mIsszmbalv3StockInfo.item_name)) {
                coordinatorLayout.setTitle(mIsszmbalv3StockInfo.item_name.trim());
            } else {
                coordinatorLayout.setTitle("商品详情");
            }
        }

        new GetIsszmbalv3SupcustInfoTask().execute();

        if (mbIsInsertData)
            new GetIsszmbalv3MaxDispersionIndexTask().execute();

        // getWindow().setEnterTransition(initContentEnterTransition());
        //getWindow().setSharedElementEnterTransition();
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.stock_id_bt:
                Intent intent = new Intent();
                intent.setClass(Isszmbalv3StockEditActivity.this, MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, ACTIVITY_RESULT_BRANDECODE);
                break;
            case R.id.rl1:
            case R.id.stock_id_et:
                new ProtogenesisInputDialog(Isszmbalv3StockEditActivity.this, mStockIdEt, "序号（计重）/ 条码（普通）", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockIdEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl2:
            case R.id.stock_name_et:
                new ProtogenesisInputDialog(Isszmbalv3StockEditActivity.this, mStockNameEt, "商品名称", null).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockNameEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl3:
            case R.id.stock_spell_et:
                new ProtogenesisInputDialog(Isszmbalv3StockEditActivity.this, mStockSpellEt, "名称拼音首字母缩写", null).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockSpellEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl4:
            case R.id.stock_unit_et:
            case R.id.stock_unit_bt:
                if (mbIsInsertData) {
                    showUnitPickWindow();
                } else {
                    AlertDialog alertDialog = new AlertDialog.Builder(Isszmbalv3StockEditActivity.this).setTitle("商品计价方式")
                            .setMessage("不可更改")
                            .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create();
                    alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
                    alertDialog.show();
                }
                break;
            case R.id.rl5:
            case R.id.stock_typeid_et:
            case R.id.stock_typeid_bt:
                showStockTypeList();
                break;
            case R.id.rl6:
            case R.id.stock_price_et:
                new ProtogenesisInputDialog(Isszmbalv3StockEditActivity.this, mStockPriceEt, "商品的进货价格", new DigitsKeyListener(false, true)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockPriceEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl7:
            case R.id.stock_retail_price_et:
                new ProtogenesisInputDialog(Isszmbalv3StockEditActivity.this, mStockRetailPriceEt, "商品的零售价格", new DigitsKeyListener(false, true)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mStockRetailPriceEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl9:
            case R.id.stock_supcustd_et:
                final String valueSrc = mStockSupcustEt.getText().toString().trim();
                new ProtogenesisInputDialog(Isszmbalv3StockEditActivity.this, mStockSupcustEt, "商品供应商", null).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        String valueDst = inputString.trim();
                        if(!valueSrc.equals(valueDst)) {
                            submitIsszmbalv3SupcustInfo(valueDst);
                        }
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.stock_supcustd_bt:
                showSupcustInfoList();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finishAfterTransition();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showUnitPickWindow() {
        final String[] items = new String[]{"普通（袋装扫码）", "计重（按公斤）"};
        AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("计价方式")
                .setSingleChoiceItems(items, mUnitType, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mUnitType = which;
                        if (mUnitType == 0) {
                            mStockUnitEt.setText("普通（袋装扫码）");
                        } else if (mUnitType == 1) {
                            mStockUnitEt.setText("计重（按公斤）");
                        }
                        if (!TextUtils.isEmpty(mIsszmbalv3MaxDispersionIndex) && mUnitType == 1) {
                            mStockIdEt.setText(mIsszmbalv3MaxDispersionIndex);
                        } else if (mUnitType == 0) {
                            mStockIdEt.setText("");
                        }
                        dialog.dismiss();
                    }
                }).create();
        alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
        alertDialog.show();
    }

    /**
     * @desc 商品所属分类选择
     * @author taoli
     * @time 2017/8/31 0031
     */
    private void showStockTypeList() {
        Map<String, String> map = this.mIsszmbalv3StockTypeMap.getMap();
        //有一个“全部”的分类需去除
        final String[] strKey = new String[map.size() - 1];
        final String[] strValue = new String[map.size() - 1];
        int len = 0;
        for (String key : map.keySet()) {
            if (!key.equals("-1")) {
                strKey[len] = key;
                strValue[len] = map.get(key);
                len++;
            }
        }

        AlertDialog alertDialog = new AlertDialog.Builder(Isszmbalv3StockEditActivity.this).setTitle("商品种类选择").setItems(strValue, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mIsszmbalv3StockInfo.item_clsno = strKey[which];
                mStockTypeidEt.setText(strValue[which]);
            }
        }).create();
        alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
        alertDialog.show();
    }

    private void showSupcustInfoList() {
        final String[] strValue = new String[mIsszmbalv3SupcustInfo.size()];
        int len = 0;
        for (Isszmbalv3SupcustInfo item : mIsszmbalv3SupcustInfo) {
            strValue[len] = item.sup_name.trim();
            len++;
        }

        AlertDialog alertDialog = new AlertDialog.Builder(Isszmbalv3StockEditActivity.this).setTitle("供应商选择").setItems(strValue, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mIsszmbalv3StockInfo.main_supcust = mIsszmbalv3SupcustInfo.get(which).supcust_no;
                mStockSupcustEt.setText(mIsszmbalv3SupcustInfo.get(which).sup_name);
            }
        }).create();
        alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
        alertDialog.show();
    }

    private void submitIsszmbalv3StockEdit() {
        String stockNoEtStr = mStockIdEt.getText().toString().trim();
        String stockNameEtStr = mStockNameEt.getText().toString().trim();
        String stockSpellEtStr = mStockSpellEt.getText().toString().trim();
        String stockPriceEtStr = mStockPriceEt.getText().toString().trim();
        String stockRetailPriceEtStr = mStockRetailPriceEt.getText().toString().trim();

        float stockRetailPrice, stockPrice;
        String nulltakeplace = null;
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = format.format(date);

        if (stockNoEtStr.length() == 0) {
            FloatTextToast.makeText(Isszmbalv3StockEditActivity.this, mStockIdEt, "商品NO不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (stockNameEtStr.length() == 0) {
            FloatTextToast.makeText(Isszmbalv3StockEditActivity.this, mStockNameEt, "商品名称不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (Utils.getStringLength(stockNameEtStr) > 40) {
            FloatTextToast.makeText(Isszmbalv3StockEditActivity.this, mStockNameEt, "商品名称输入过长!", FloatTextToast.LENGTH_SHORT).show();
            return;
        }

        if (stockSpellEtStr.length() == 0) {
            FloatTextToast.makeText(Isszmbalv3StockEditActivity.this, mStockSpellEt, "商品名称首字母缩写不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (Utils.getStringLength(stockSpellEtStr) > 10) {
            FloatTextToast.makeText(Isszmbalv3StockEditActivity.this, mStockSpellEt, "商品名称首字母缩写过长!", FloatTextToast.LENGTH_SHORT).show();
            return;
        }

        if (mUnitType == -1) {
            FloatTextToast.makeText(Isszmbalv3StockEditActivity.this, mStockUnitEt, "未选择计重方式！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }

        try {
            stockPrice = Float.parseFloat(stockPriceEtStr);
            stockRetailPrice = Float.parseFloat(stockRetailPriceEtStr);
            if (stockPrice >= stockRetailPrice) {
                showTipsDialog("销售价格不能小于等于进货价");
                return;
            }
        } catch (Exception e) {
            FloatTextToast.makeText(Isszmbalv3StockEditActivity.this, mStockRetailPriceEt, "商品进货/零售价格输入错误！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }

        //String name = Utils.getMaxLenString(stockNameEtStr, 40);
        String subname = Utils.getMaxLenString(stockNameEtStr, 20);
        //String spell = Utils.getMaxLenString(stockSpellEtStr, 10);

        try {
            ContentValues initialValues = new ContentValues();
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_no, stockNoEtStr.trim());
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_subno, "");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_name, stockNameEtStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_subname, subname);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_clsno, mIsszmbalv3StockInfo.item_clsno);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_brand, "PP");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_brandname, "PM");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_unit_no, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_size, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_price, stockPrice);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_sale_price, stockRetailPrice);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_combine_sta, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_status, "1");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_display_flag, "1");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_po_cycle, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_so_cycle, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_automin_flag, "1");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_en_dis, "1");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_change_price, "1");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_purchase_tax, 0.17);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_sale_tax, 0.17);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_purchase_spec, 1.0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_shipment_spec, 1.0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_item_supcust, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_main_supcust, mIsszmbalv3StockInfo.main_supcust);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_item_stock, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_build_date, dateStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_modify_date, dateStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_stop_date, new String());
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_abc, "C");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_branch_price, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_item_rem, stockSpellEtStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_vip_price, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_sale_min_price, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_com_flag, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_vip_acc_flag, mIsszmbalv3StockInfo.vip_acc_flag);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_vip_acc_num, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_dpfm_type, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_return_rate, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_update_date, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_pro_code1, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_pro_code2, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_pro_code3, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_pro_code4, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_pro_code5, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_pro_code6, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_item_picture, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_sale_flag, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_scheme_price, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_vip_price2, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_vip_price3, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_vip_price4, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_vip_price5, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_valid_days, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_memo, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_item_com, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_product_area, nulltakeplace);
            if (mUnitType == 0) { //扫码
                initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_measure_flag, "0");
            } else if (mUnitType == 1) { //散称
                initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_measure_flag, "1");
            }
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_item_sup_flag, "A");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_sup_rate, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_picture_type, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price1, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price2, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price3, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price4, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price5, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price6, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price7, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_base_price8, nulltakeplace);
            if (mUnitType == 0) { //扫码
                //不需要插入key ISSZMBALV3_t_bd_item_new_oper_id 和 ISSZMBALV3_t_bd_item_modify_oper_id
            } else if (mUnitType == 1) { //散称
                initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_new_oper_id, "1001");
                initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_modify_oper_id, "1001");
            }
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_en_gift, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_promote_flag, "Y");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_allow_flag, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_hand_flag, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_alert_day1, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_alert_day2, nulltakeplace);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_fresh_sque, nulltakeplace);
            new SubmitIsszmbalv3StockInfoTask().execute(initialValues);
            new SubmitIsszmbalv3StockInfoPicDesc().execute(stockNoEtStr.trim());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void uploadPicture(String stockNoEtStr, Auth auth, File file) {
        String key = BarApplication.mStoreName + "_" + "stockNo_" + stockNoEtStr + ".jpg";
        String token = auth.uploadToken(BarApplication.Qiniu_Bucket);
        UploadManager uploadManager = new UploadManager(qiniuConfig);
        uploadManager.put(file, key, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, final ResponseInfo info, JSONObject res) {
                if (info.isOK()) {
                    Isszmbalv3StockEditActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(Isszmbalv3StockEditActivity.this, "图片提交成功！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    Isszmbalv3StockEditActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(Isszmbalv3StockEditActivity.this, "图片提交失败，" + info.error, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }, new UploadOptions(null, null, false, new UpProgressHandler() {
            public void progress(String key, double percent) {
            }
        }, null));
    }

    public void showTipsDialog(final String tips) {
        DialogUtil.showTipsDialog(this, tips, new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    private void showWaitDialog(final String tips) {
        DialogUtil.showWaitDialog(this, tips);
    }

    private void hideWaitDialog() {
        DialogUtil.hideWaitDialog();
    }

    private void getPicDesc(String stockNo, final ImageView iv) {
        //String stockUrl = BarApplication.Qiniu_BaseDownloadHost + BarApplication.mStoreName + "_" + "stockNo_" + stockNo + ".jpg";
        //GlideUtils.LoadImage(getActivity(), stockUrl, iv);
        String path = "file://" + mSavePictureDirPath + BarApplication.mStoreName + "_" + "stockNo_" + stockNo + ".jpg";
        Glide.with(getActivity()).load(path).thumbnail(1.0f).into(iv);
    }

    private void pickPicDescImage() {
        if (mPickImageDialog == null) {
            mPickImageDialog = new PickImageDialog(this);
            mPickImageDialog.setItemClickListener(new PickImageDialog.OnItemClick() {
                @Override
                public void onItemClick(int position) {
                    if (position == 0) {
                        //单选打开相册 带配置
                        mPhotoUtils.selectPicture(Isszmbalv3StockEditActivity.this);
                    } else if (position == 1) {
                        //使用拍照 带配置
                        mPhotoUtils.takePicture(Isszmbalv3StockEditActivity.this);
                    }
                }
            });
            mPickImageDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                }
            });
            Window window = mPickImageDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.dialog_bottom_anim_style);
        }
        mPickImageDialog.show();
    }

    private class SubmitIsszmbalv3StockInfoTask extends AsyncTask<ContentValues, Void, String> {
        public SubmitIsszmbalv3StockInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showWaitDialog("正在处理，请稍等...");
        }

        @Override
        protected String doInBackground(ContentValues... params) {
            if (Isszmbalv3StockEditActivity.this.isFinishing()) {
                return "";
            }
            ContentValues initialValues = params[0];
            long row = -1;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                if (mbIsInsertData) {
                    row = DatabaseManager.insertIsszmbalv3StockInfoFromSqlServer(Isszmbalv3StockEditActivity.this, initialValues);
                } else {
                    row = DatabaseManager.replaceIsszmbalv3StockInfoFromSqlServer(Isszmbalv3StockEditActivity.this, initialValues);
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    row = DatabaseManager.deleteIsszmbalv3StockInfoFromSqlServer(Isszmbalv3StockEditActivity.this, (String) initialValues.get(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_no));
                    if (row == -1) {
                        return String.valueOf(row);
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    row = DatabaseManager.insertIsszmbalv3StockInfoFromSqlServer(Isszmbalv3StockEditActivity.this, initialValues);
                    // row = DatabaseManager.replaceIsszmbalv3StockInfoFromSqlServer(Isszmbalv3StockEditActivity.this, initialValues);
                }
            }
            //插入到历史记录
            {
                String itemno = (String) initialValues.get(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_no);
                initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_no, String.format("%1$-20s", itemno));
                long r = DatabaseManager.insertIsszmbalv3StockInfoFromHistory(Isszmbalv3StockEditActivity.this, initialValues);
            }
            return String.valueOf(row);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (Isszmbalv3StockEditActivity.this.isFinishing()) {
                return;
            }
            hideWaitDialog();
            if (result.contains("-1")) {
                if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                    showTipsDialog("对不起，信息修改失败，将中文名称截短再试。");
                }
            } else {
                showTipsDialog("恭喜，成功修改了" + result + "条数据。");
                setResult(RESULT_OK);
            }
        }
    }

    private class GetIsszmbalv3MaxDispersionIndexTask extends AsyncTask<Void, Void, String> {
        public GetIsszmbalv3MaxDispersionIndexTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            String index = "";
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                index = DatabaseManager.getIsszmbalv3MaxDispersionIndex(Isszmbalv3StockEditActivity.this);
            }
            return index;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            mIsszmbalv3MaxDispersionIndex = result;
            if (!TextUtils.isEmpty(mIsszmbalv3MaxDispersionIndex) && mUnitType == 1) {
                mStockIdEt.setText(mIsszmbalv3MaxDispersionIndex);
            }
        }
    }

    private void submitIsszmbalv3SupcustInfo(String stockSupcustString) {
        if (stockSupcustString.length() == 0) {
            FloatTextToast.makeText(Isszmbalv3StockEditActivity.this, mStockSupcustEt, "供应商不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        try {
            ContentValues initialValues = new ContentValues();
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_supcust_no, String.valueOf(mIsszmbalv3SupcustInfo.size() + 1));
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_sup_name, stockSupcustString);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_sup_type, "1");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_supcust_flag, "S");
            new SubmitIsszmbalv3SupcustInfoTask().execute(initialValues);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class SubmitIsszmbalv3SupcustInfoTask extends AsyncTask<ContentValues, Void, ContentValues> {
        public SubmitIsszmbalv3SupcustInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showWaitDialog("正在新增供应商，请稍等...");
        }

        @Override
        protected ContentValues doInBackground(ContentValues... params) {
            if (Isszmbalv3StockEditActivity.this.isFinishing()) {
                return null;
            }
            ContentValues initialValues = params[0];
            long row = -1;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                row = DatabaseManager.insertIsszmbalv3SupcustInfo(Isszmbalv3StockEditActivity.this, initialValues);
                //row = DatabaseManager.updateIsszmbalv3SupcustInfo(Isszmbalv3StockEditActivity.this, initialValues);
            }
            if(row == -1){
                initialValues.put(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_supcust_no, "-1");
            }
            return initialValues;
        }

        @Override
        protected void onPostExecute(ContentValues result) {
            super.onPostExecute(result);
            if( result == null ){
                return;
            }
            if (Isszmbalv3StockEditActivity.this.isFinishing()) {
                return;
            }
            hideWaitDialog();
            if (((String)result.get(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_supcust_no)).contains("-1")) {
                if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                    showTipsDialog("对不起，新增供应商信息失败。");
                }
            } else {
                setResult(RESULT_OK);
                mIsszmbalv3StockInfo.main_supcust = (String)result.get(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_supcust_no);
                new GetIsszmbalv3SupcustInfoTask().execute();
            }
        }
    }

    private class GetIsszmbalv3SupcustInfoTask extends AsyncTask<Void, Void, String> {
        public GetIsszmbalv3SupcustInfoTask() {

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            if (getActivity().isFinishing()) {
                return null;
            }
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                //获取供应商信息
                List<Isszmbalv3SupcustInfo> isszmbalv3SupcustInfoList = DatabaseManager.getIsszmbalv3SupcustInfoListFromSqlServer(getActivity());
                mIsszmbalv3SupcustInfo = isszmbalv3SupcustInfoList;
            } else {
                //获取供应商信息
                List<Isszmbalv3SupcustInfo> isszmbalv3SupcustInfoList = DatabaseManager.getIsszmbalv3SupcustInfoListFromLocal(getActivity());
                mIsszmbalv3SupcustInfo = isszmbalv3SupcustInfoList;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (getActivity().isFinishing()) {
                return;
            }
            if( mIsszmbalv3StockInfo != null ) {
                for (int i = 0; i < mIsszmbalv3SupcustInfo.size(); i++) {
                    if (mIsszmbalv3SupcustInfo.get(i).supcust_no.contains(mIsszmbalv3StockInfo.main_supcust)) {
                        mIsszmbalv3StockInfo.main_supcust = mIsszmbalv3SupcustInfo.get(i).supcust_no;
                        mStockSupcustEt.setText(mIsszmbalv3SupcustInfo.get(i).sup_name.trim());
                    }
                }
            }
        }
    }

    private class SubmitIsszmbalv3StockInfoPicDesc extends AsyncTask<String, Void, String> {
        public SubmitIsszmbalv3StockInfoPicDesc() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            final String stockNoEtStr = params[0].trim();
            if (!TextUtils.isEmpty(mPicDescPath)) {
                String picPath = mPicDescPath;
                final File file = new File(picPath);
                if (file.exists()) {
                    final Auth auth = Auth.create(BarApplication.Qiniu_AccessKey, BarApplication.Qiniu_SecretKey);
                    String entry = BarApplication.Qiniu_Bucket + ":" + BarApplication.mStoreName + "_" + "stockNo_" + stockNoEtStr + ".jpg";
                    String encodedEntryURI = "http://rs.qiniu.com/delete/" + UrlSafeBase64.encodeToString(entry);
                    String accessToken = auth.signRequest(encodedEntryURI, null, "application/x-www-form-urlencoded");
                    String authorization = "QBox " + accessToken;
                    NetHelper.deleteQiniuRes(Isszmbalv3StockEditActivity.this, encodedEntryURI, "rs.qiniu.com", "application/x-www-form-urlencoded", authorization, new NetCallback<ServiceResult>() {
                        @Override
                        public void onSucceed(final int code) {
                            uploadPicture(stockNoEtStr, auth, file);
                        }

                        @Override
                        public void onSucceed(ServiceResult rspData) {
                            uploadPicture(stockNoEtStr, auth, file);
                        }

                        @Override
                        public void onFailed(String msg) {

                        }
                    }, QiniuControl.class);
                }
            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ACTIVITY_RESULT_BRANDECODE:
                if (data != null) {
                    if (mStockIdEt != null) {
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            //mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                            mStockIdEt.setText(bundle.getString("result"));
                        }
                    }
                }
                break;
            case PhotoUtils.INTENT_CROP:
            case PhotoUtils.INTENT_TAKE:
            case PhotoUtils.INTENT_SELECT:
                mPhotoUtils.onActivityResult(Isszmbalv3StockEditActivity.this, requestCode, resultCode, data);
                break;
        }
    }
}
